/*
 * Copyright (C) 2009, 2010, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.b3log.nide.jsonrpc;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.b3log.latke.action.ActionException;
import org.b3log.latke.jsonrpc.AbstractJSONRpcService;
import org.b3log.latke.service.ServiceException;
import org.b3log.nide.model.source.java.JavaSourceFile;
import org.b3log.nide.model.Project;
import org.b3log.nide.model.ProjectSpace;
import org.b3log.nide.service.ProjectManager;
import org.b3log.nide.service.maven.MavenManager;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * <a href="http://maven.apache.org">Maven</a> service for JavaScript
 * client.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.5, Nov 29, 2010
 */
public final class MavenService extends AbstractJSONRpcService {

    /**
     * Default serial version uid.
     */
    private static final long serialVersionUID = 1L;
    /**
     * Logger.
     */
    private static final Logger LOGGER =
            Logger.getLogger(MavenService.class.getName());
    /**
     * Project manager.
     */
    private ProjectManager projectManager = ProjectManager.INSTANCE;
    /**
     * Maven manager.
     */
    private MavenManager mavenManager = MavenManager.INSTANCE;

    /**
     * Generates a sample quickstart Maven project with the specified request
     * json object that depicts the initialization arguments of this sample
     * project.
     *
     * @param requestJSONObject the specified request json object, for example:
     * <pre>
     * {
     *     "projectGroupId": "org.b3log",
     *     "projectArtifactId": "l0y0l",
     *     "projectVersion": "1.0.0"
     * }
     * </pre>
     * @param request the specified http servlet request
     * @return generates sample project execution result, for example:
     * <pre>
     * {
     * TODO: javadoc
     * }
     * </pre>
     * @throws ActionException action exception
     */
    public JSONObject genSampleProject(final JSONObject requestJSONObject,
                                       final HttpServletRequest request)
            throws ActionException {
        final String projectParentDir = ProjectManager.getProjectsDir();

        try {
            requestJSONObject.put(Project.PROJECT_PARENT_DIR, projectParentDir);
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        try {
            mavenManager.genSampleProject(requestJSONObject);
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        final JSONObject ret = new JSONObject();

        return ret;
    }

    /**
     * Cleans and builds a project by the specified request json object.
     *
     * @param requestJSONObject the specified json object, for example:
     * <pre>
     * {
     *     "projectArtifactId": "nide-test"
     * }
     * </pre>
     * @param request the specified http servlet request
     * @return clean and build execution result, for example:
     * <pre>
     * {
     * TODO: javadoc
     * }
     * </pre>
     * @throws ActionException action exception
     */
    public JSONObject cleanAndBuild(final JSONObject requestJSONObject,
                                    final HttpServletRequest request)
            throws ActionException {
        String projectBaseDir = null;
        JSONObject projectSpace = null;

        try {
            projectSpace = projectManager.getProjectSpace();
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        final JSONObject project = new JSONObject();

        try {
            final String artifactId = requestJSONObject.getString(
                    Project.PROJECT_ARTIFACT_ID);
            projectBaseDir =
                    projectSpace.getString(ProjectSpace.PROJECT_SPACE_DIR);
            projectBaseDir += artifactId;

            project.put(Project.PROJECT_BASE_DIR, projectBaseDir);
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }


        final JSONObject ret = new JSONObject();

        try {
            mavenManager.cleanProject(project);
            mavenManager.installProject(project);
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        return ret;
    }

    /**
     * Runs a Java file by the specified request json object.
     *
     * @param requestJSONObject the specified json object, for example:
     * <pre>
     * {
     *     "projectArtifactId": "nide",
     *     "mainClass": "org.b3log.nide.Nide"
     * }
     * </pre>
     * @param request the specified http servlet request
     * @return clean and build execution result, for example:
     * <pre>
     * {
     * TODO: javadoc
     * }
     * </pre>
     * @throws ActionException action exception
     */
    public JSONObject runFile(final JSONObject requestJSONObject,
                              final HttpServletRequest request)
            throws ActionException {
        String projectBaseDir = null;
        String mainClass = null;
        JSONObject projectSpace = null;

        try {
            projectSpace = projectManager.getProjectSpace();
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        final JSONObject javaFile = new JSONObject();

        try {
            final String artifactId = requestJSONObject.getString(
                    Project.PROJECT_ARTIFACT_ID);
            projectBaseDir =
                    projectSpace.getString(ProjectSpace.PROJECT_SPACE_DIR);
            projectBaseDir += artifactId;

            javaFile.put(Project.PROJECT_BASE_DIR, projectBaseDir);

            mainClass = requestJSONObject.getString(
                    JavaSourceFile.JAVA_MAIN_CLASS);
            javaFile.put(JavaSourceFile.JAVA_MAIN_CLASS, mainClass);
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        final JSONObject ret = new JSONObject();

        try {
            mavenManager.runJavaFile(javaFile);
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        return ret;
    }
}
